package com.lpx.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 继承WebSecurityConfigurerAdapter 类  重写方法  设置 用户名 密码
 * 配置类实现  用户名  密码  登录
 * @author ccit
 *
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	
//	@Override
//	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//		BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//		String passwString = bCryptPasswordEncoder.encode("123");
//		
//		auth.inMemoryAuthentication().withUser("user").password(passwString).roles("");
//	}
	
	@Autowired
	private UserDetailsService userDetailsService; 
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
	}
	
	
	@Bean
	PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	/**
	 * 设置自定义登陆页面（默认为security自带的登陆页面）
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//配置没有权限访问自定义跳转的页面
		http.exceptionHandling()
		.accessDeniedPage("/403.html");
		//退出配置
        http.logout().logoutUrl("/logout")
             .logoutSuccessUrl("/page/logout")
             .permitAll();
		http.formLogin()
			.loginPage("/login.html")//自定义登陆页面	前后端分离的  访问地址 ip:端口号\路径\页面.html
			.loginProcessingUrl("/user/login")//登录访问路径controller
			.defaultSuccessUrl("/page/index").permitAll()//登录成功之后访问的页面  permitAll允许设置
			.and().authorizeRequests().antMatchers("/page/hello","/user/login").permitAll()//设置  不需要登录认证  就可以访问的接口
			//.antMatchers("/page/index").hasAuthority("admins","manger")//只有有admins与manger权限的  可以访问这个路径 与的关系
			.antMatchers("/page/index").hasAnyAuthority("admin","manger")//admin 或 manger 都可以访问  或的关系
//			.antMatchers("/page/index").hasRole("teacher")
			.antMatchers("/page/index").hasAnyAuthority("teacher","student")
			.anyRequest().authenticated()
			.and().csrf().disable()//关闭 csrf的 防护
			;
	
	}
}
